import 'dart:async';

import 'package:basic_common/common_exports.dart';
import 'package:basic_common/global_getx.dart';
import 'package:basic_common/time_tool.dart';
import 'package:basic_message/modle/chat_data.dart';
import 'package:basic_message/modle/chat_data_list.dart';
import 'package:basic_modle/upload_data.dart';

class ChatController extends GetxController {
  int status = 0;
  TextEditingController inputController = TextEditingController();
  final chatList = <Chatdata>[].obs;

  final isShowInput = true.obs; //显示输入框
  final isShowBottom = false.obs; //是否显示底部图片选择

  final selImgPath = ''.obs; //图片路径
  final patientNo = ''.obs;
  final pPhotoUrl = ''.obs; //患者头像
  final dPhotoUrl = ''.obs; //医生头像
  Timer? mTimer;
  Set<String> timeList = <String>{}; //时间数组
  final isShowTime = false.obs;

  /// 语音按钮点击事件
  void switchVoice() {
    // isShowInput.value = false;
  }
  void selectImg() {
    isShowBottom.value = !isShowBottom.value;
  }

// type 0 拍照 1 相册
  showSelectImg(int type) {
    // BottomImagePickerTool.showBottomSheet(
    //     onCamera: () => getCameraImgs(), onGallery: () => getImgs());
    if (type == 1) {
      getCameraImgs();
    } else {
      getImgs();
    }
  }

  /// 相机拍照
  getCameraImgs() async {
    XFile? _image;
    final picker = ImagePicker();
    _image = await picker.pickImage(source: ImageSource.camera);
    selImgPath.value = await uploadSingleFile(_image!.path);
    sendMsgToP(msgType: '2');
  }
  // 发送图片消息

  /// 选择相册图片
  getImgs() async {
    XFile? _image;
    final picker = ImagePicker();
    _image = await picker.pickImage(source: ImageSource.gallery);
    selImgPath.value = await uploadSingleFile(_image!.path);
    sendMsgToP(msgType: '2');
  }

  /// 单个图片上传
  Future<String> uploadSingleFile(String path) async {
    String uId = globalGetx.userId.value ?? '';
    if (uId.isEmpty) {
      ToastUtils.toast("发送图片失败");
      return '';
    }
    UploadData res = await ApiService().uploadSingle(params: {
      "file": await MultipartFile.fromFile(path),
      "domain": 'fw/${uId}'
    });
    if (res.errCode == 0) {
      return res.uri!;
    }
    return '';
  }

  /// 获取会话列表
  void getChatList() async {
    chatList != [];
    String dNum = globalGetx.doctorNo.value;
    String pNum = patientNo.value; //乔博
    if (dNum.isEmpty || pNum.isEmpty) {
      ToastUtils.toast("医生患者ID不能为空");
      return;
    }
    HttpData res = await ApiService().getChatMsgList(
        data: {"isSignDoctor": "0", "doctorNo": dNum, "patientNo": pNum});
    if (res.code == 1) {
      ChatDataList listData = ChatDataList.fromJson(res.toJson());
      pPhotoUrl.value = listData.data!.patientAvatarUrl!;
      dPhotoUrl.value = listData.data!.doctorAvatarUrl!;
      if (listData.data != null && listData.data!.chatList!.length > 0) {
        List<ChatList>? dataList = listData.data!.chatList;
        if (dataList!.length > 0) {
          if (chatList.length > 0) {
            chatList.clear();
          }

          for (int i = 0; i < dataList.length; i++) {
            ChatList item = dataList[i];
            String content = item.msgContent!;
            String chatType = item.msgType!;
            String initaType = item.initiatorType!; //发起人
            String time = TimeTool.strToDateHHMM(item.createTime!); //时间

            for (int j = 0; j < chatList.length; j++) {
              if (time == chatList[j].time) {
                isShowTime.value = false;
              } else {
                isShowTime.value = true;
              }
            }
            chatList.add(Chatdata(initaType == '1' ? true : false, content,
                chatType == '1' ? 1 : 2, time, isShowTime.value));
          }
          update(['updateMsg']);
        }
      }
      update(['updateMsg']);
    }
  }

  /// 发送消息给患者
  /// msgType 1 文本 2 图片
  void sendMsgToP({required String msgType}) async {
    String msgContent = inputController.text;
    String imgPath = selImgPath.value;

    String dNum = globalGetx.doctorNo.value;
    String pNum = patientNo.value;
    if (dNum.isEmpty || pNum.isEmpty) {
      ToastUtils.toast("医生患者ID不能为空");
      return;
    }
    if (msgType == "1" && msgContent.isEmpty) {
      ToastUtils.toast("消息不能为空");
      return;
    }
    HttpData res = await ApiService().senMsgToPatient(data: {
      "patientNo": pNum,
      "doctorNo": dNum,
      "initiatorType": "1",
      "msgContent": msgType == '1' ? msgContent : imgPath,
      "msgType": msgType
    });

    if (res.code == 1 && msgType == '1') {
      chatList.add(Chatdata(true, msgContent, 1, "", false));
      inputController.text = '';
    } else if (res.code == 1 && msgType == '2') {
      chatList.add(Chatdata(true, imgPath, 2, "", false));
    }
    update(['updateMsg']);
  }

  void navToPresc() {
    Get.toNamed(AppRoutes.prescription, arguments: {
      "pNo": patientNo.value,
    });
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    patientNo.value = Get.arguments['patientNo'];
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    getChatList();

    mTimer = Timer.periodic(Duration(seconds: 2), (timer) {
      getChatList();
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    mTimer!.cancel();
    mTimer = null;
    super.onClose();
  }
}
